package com.xiaoyun.utils;


import cn.hutool.core.util.XmlUtil;
import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

public class XmlUtils {


    public static <T> T xml2Object(String result, Class<T> clazz) throws IOException {
        return XmlUtil.xmlToBean(XmlUtil.readXML(result), clazz);
    }

    public static <T> T xml2Object(InputStream inputStream, Class<T> clazz) throws IOException {
        return XmlUtil.xmlToBean(XmlUtil.readXML(inputStream), clazz);
    }

    public static void main(String[] args) throws Exception {
        String xmlStr = "<book>\n" +
                "        <author>Jack Herrington</author>\n" +
                "        <title>PHP Hacks</title>\n" +
                "        <publisher>O'Reilly</publisher>\n" +
                "    </book>";
        BookTest bookTest = xml2Object(xmlStr, BookTest.class);
        System.out.println(bookTest);
    }


    public static <T> T mapToObject(Map map, Class<T> beanClass) throws  IllegalAccessException, InstantiationException {
        if (map == null)
            return null;
        Object obj = beanClass.newInstance();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }
            field.setAccessible(true);
            if (map.containsKey(field.getName())) {
                field.set(obj, map.get(field.getName()));
            }
        }
        return (T) obj;
    }


    @Data
    static class BookTest {
        private String author;
        private String title;
        private String publisher;
    }


}
